const http = require("http");
const { resolve } = require("path");
const multiparty = require("multiparty");
const fse = require("fs-extra");
const server = http.createServer();
const UPLOAD_DIR = resolve(__dirname, ".", "target");
server.on("request", async (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");

  if (req.url === "/") {
    const multipart = new multiparty.Form();
    multipart.parse(req, async (err, fields, files) => {
      if (err) return;
      const [chunk] = files.chunk;
      const [fileName] = fields.fileName;
      /**
       * dir_name 上传过来的文件名
       * chunk_Dir 上传目录target下的文件夹
       */
      const dir_name = fileName.split("-")[0];
      const chunk_Dir = resolve(UPLOAD_DIR, dir_name);
      if (!fse.existsSync(chunk_Dir)) {
        await fse.mkdirs(chunk_Dir);
      }
      // chunk.path 文件的缓冲区
      await fse.move(chunk.path, `${chunk_Dir}/${fileName}`);
      console.log("files:", files);
      console.log("fields:", fields);
    });
  }
});

server.listen(3000, () => console.log("http://localhost:3000"));
